package ru.avn.devtool4j.spi.writers.impl;

import java.util.Arrays;
import java.util.List;

public class DslClassWriter {

	private StringBuilder builder;
	
	private int tab = 0;
	
	public static DslClassWriter getWriter() {
		DslClassWriter classWriter = new DslClassWriter();
		classWriter.builder = new StringBuilder();
		return classWriter;
	}
	
	public DslClassWriter writeLine(String line) {
		
		if (line == null || line.trim().isEmpty()) {
			return this;
		}
		
		addTabs();
		builder.append(line.trim());
		endLine();
		return this;
	}
	
	
	public DslClassWriter writeLine(String line, boolean conditional) {
		if (!conditional) {
			return this;
		} else {
			return writeLine(line);
		}
	}
	
	public DslClassWriter write(String string, boolean conditional) {
		if (!conditional) {
			return this;
		} else {
			return write(string);
		}
	}
	
	
	public DslClassWriter write(String string) {
		builder.append(string)
		.append(" ");
		return this;
	}
	
	public DslClassWriter writeLine(String[] lines) {
		return writeLines(Arrays.asList(lines));
	}
	
	public DslClassWriter writeLines(List<String> lines) {
		if (lines!= null) {
			for (String line : lines) {
				writeLine(line);
			}
		}
		return this;
	}
	
	public DslClassWriter nextLine() {
		builder.append("\n");
		return this;
	}
	
	public DslClassWriter newBlock() {
		builder.append("{\n");
		tab++;
		return this;
	}
	
	public DslClassWriter newBlock(String blockname) {
		addTabs();
		write(blockname);
		builder.append("{\n");
		tab++;
		return this;
	}
	
	public DslClassWriter closeBlock() {
		tab--;
		addTabs();
		builder.append("}\n");
		return this;
	}
	
	
	private void addTabs() {
		for (int i = 0; i < tab; i ++) {
			builder.append("\t");
		}
	}
	
	private void endLine() {
		builder.append(";\n");
	}
	
	
	public String build() {
		return builder.toString();
	}
}
